package com.xhb.ui.download;

import cn.hutool.core.util.IdUtil;
import com.teamdev.jxbrowser.browser.callback.StartDownloadCallback;
import com.teamdev.jxbrowser.download.Download;
import com.teamdev.jxbrowser.download.DownloadState;
import com.teamdev.jxbrowser.download.event.DownloadFinished;
import com.teamdev.jxbrowser.download.event.DownloadInterruptReason;
import com.teamdev.jxbrowser.download.event.DownloadInterrupted;
import com.teamdev.jxbrowser.download.event.DownloadUpdated;
import com.xhb.biz.config.APPConfig;
import com.xhb.biz.po.DownloadPO;
import com.xhb.biz.service.DownloadFileService;
import org.noear.solon.Solon;

import java.nio.file.Paths;

/**
 * 文件下载回调
 */
public class EasyStartDownloadCallback implements StartDownloadCallback {

    @Override
    public void on(Params params, Action action) {
        //要下载的对象
        Download download = params.download();
        String downloadId = IdUtil.simpleUUID();
        String savePath = APPConfig.downloadPath + download.target().suggestedFileName();
        action.download(Paths.get(savePath));

        //截取文件类型，最后一个. 之后的名称
        String fileName = download.target().suggestedFileName();
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        //添加下载文件
        Solon.context().getBeanAsync(DownloadFileService.class, service -> {
            DownloadPO savePO = DownloadPO.builder()
                    .id(downloadId)
                    .fileName(fileName)
                    .filePath(savePath)
                    .url(download.target().url())
                    .type(fileType.toLowerCase())
                    .status(download.state().getNumber())
                    .progressBar(0)
                    .totalBytes(0l)
                    .receivedBytes(0l)
                    .build();
            service.insert(savePO);
            if (!BottomDownloadBar.getInstance().getVisiable()) {
                BottomDownloadBar.getInstance().clear();
            }
            BottomDownloadBar.getInstance().add(savePO);
            BottomDownloadBar.getInstance().open();
        });
        //添加下载消息
        DownloadManager.getInstance().getIdDownloadMap().put(downloadId, download);
        //需要更新的对象
        DownloadPO updatePO = DownloadPO.builder().id(downloadId).build();

        //跟踪下载进度
        download.on(DownloadUpdated.class, event -> {
            // Print download progress in percents.
            event.progress().ifPresent(progress ->
                    updatePO.setProgressBar((int) (progress.value())));
            // The current download speed estimate in bytes/second.
            updatePO.setCurrentSpeed(event.currentSpeed());
            // The total size of a file in bytes.
            updatePO.setTotalBytes(event.totalBytes());
            // The number or received (downloaded) bytes.
            updatePO.setReceivedBytes(event.receivedBytes());
            //更新库中数据
            Solon.context().getBeanAsync(DownloadFileService.class, bean -> {
                bean.updateAsync(updatePO);
            });
        });

        //下载完成 后需要更新数据 并且 删除掉DownloadManager 中的对象
        download.on(DownloadFinished.class, event -> {
            DownloadManager.getInstance().removeDownload(downloadId);
            //更新库中数据
            Solon.context().getBeanAsync(DownloadFileService.class, bean -> {
                //设置状态为【完成】
                updatePO.setStatus(DownloadState.COMPLETE_VALUE);
                bean.updateAsync(updatePO);
            });
        });

        //下载中断 后需要删除数据 并且 删除掉DownloadManager 中的对象
        download.on(DownloadInterrupted.class, event -> {
            // The interrupt reason such as file access denied, network failed, etc.
            DownloadInterruptReason reason = event.reason();
            DownloadManager.getInstance().removeDownload(downloadId);
            //更新库中数据
            Solon.context().getBeanAsync(DownloadFileService.class, bean -> {
                bean.deleteAsync(updatePO);
            });
        });

    }
}
